package widgets

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
)

// ClickableTitle 可点击的标题组件
type ClickableTitle struct {
	widget.BaseWidget
	title     string
	icon      string
	isOpen    bool
	onToggled func(bool)
	rightSide *fyne.Container
	container *fyne.Container
}

// NewClickableTitle 创建可点击的标题
func NewClickableTitle(title, icon string, isOpen bool, onToggled func(bool)) *ClickableTitle {
	ct := &ClickableTitle{
		title:     title,
		icon:      icon,
		isOpen:    isOpen,
		onToggled: onToggled,
		rightSide: container.NewHBox(),
	}

	ct.container = container.NewBorder(nil, nil,
		container.NewHBox(
			widget.NewIcon(theme.NavigateNextIcon()),
			widget.NewLabel(ct.getTitleText()),
		),
		ct.rightSide,
		nil,
	)

	// 根据展开状态调整图标
	ct.updateIcon()

	ct.ExtendBaseWidget(ct)
	return ct
}

// getTitleText 获取标题文本
func (ct *ClickableTitle) getTitleText() string {
	return ct.icon + " " + ct.title
}

// updateIcon 更新图标方向
func (ct *ClickableTitle) updateIcon() {
	if ct.container != nil && len(ct.container.Objects) > 0 {
		if icon, ok := ct.container.Objects[0].(*widget.Icon); ok {
			if ct.isOpen {
				icon.SetResource(theme.MenuDropDownIcon())
			} else {
				icon.SetResource(theme.MenuExpandIcon())
			}
		}
	}
}

// Tapped 点击事件处理
func (ct *ClickableTitle) Tapped(*fyne.PointEvent) {
	ct.isOpen = !ct.isOpen
	ct.updateIcon()
	if ct.onToggled != nil {
		ct.onToggled(ct.isOpen)
	}
}

// CreateRenderer 创建渲染器
func (ct *ClickableTitle) CreateRenderer() fyne.WidgetRenderer {
	return widget.NewSimpleRenderer(ct.container)
}

// SetState 设置展开状态
func (ct *ClickableTitle) SetState(open bool) {
	if ct.isOpen != open {
		ct.isOpen = open
		ct.updateIcon()
	}
}

// AddRightSide 添加右侧组件
func (ct *ClickableTitle) AddRightSide(objects ...fyne.CanvasObject) {
	for _, obj := range objects {
		ct.rightSide.Add(obj)
	}
}
